package router

import (
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"go-devops/common"
	"log"
	"runtime"
)

func AuthHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		path := c.Request.URL.Path
		if common.NoAuthPath[path] {
			c.Next()
			return
		}

		log.Println("AuthHandler path:", path)
		tokenString := c.GetHeader(common.TOKEN)
		log.Println("路由鉴权处理 token=", tokenString)

		token, err := common.ValidateToken(tokenString)
		if err != nil {
			c.Abort()
			common.Fail(c, common.ErrAuth)
			return
		}

		if claims, ok := token.Claims.(jwt.MapClaims); ok {
			username := claims[common.USERNAME].(string)
			c.Set(common.USERNAME, username)
		}
		c.Next()
	}
}

func GlobalExceptionHandler(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			stack := make([]byte, 4096)
			length := runtime.Stack(stack, false)
			log.Printf("Panic occurred: %v\nStack trace:\n%s", err, stack[:length])
			c.Abort()
			common.Error(c)
			return
		}
	}()
	c.Next()
}
